Lesson 3 - Statements and expressions

There are two statements which you will already be familiar with. That is print and assignment. Both of these statements have a specific syntax. The code sample below shows how print is structured


# print expression
# expression can be a single value or a calculation 
print "hello"
print 10 + 4
print (x > y)
print  str(10 + 4)) + "hello"


Expressions are evaluated before the statement. They are evaluated from left to right and anything inside brackets is always done first. The line print str(10 + 4)) + "hello" will do "10 + 4" first, then str() and finally the "hello". This results in the output "14hello". When using brackets it is very important to ensure that they are balanced. Balanced brackets means that there are the exact same number of open and close brackets. The expression below will be executed in the following order -

  1. 10 + 5
  2. 15 - 10
  3. 8 + 2
  4. 5 + 10

print ((10 +5) - 10) + (8 + 2)


Assignment works very similar to print. The expression must always be on the right hand side and will always be evaulated first. The expression will then be evaluated in the exact same order. The code example below demonstrates this. Although expressions are always done from left to right this does not mean that the left part will be evaulated first. In the example below we can see that 6/3 is evaluated first. The reason for this is that there is nothing for x + to be added to yet! So until 6/3 is calculated there is nothing to add.


x = (10 + 4) * 5 # 10 + 4 evaulated first
y = x + (6 / 3) # in this case 6 / 3 is evaluated first!
print x + y 

Logic expressions follow the same rules as normal expressions. In fact they are treated exactly the same.

Key learning points